package com.android.lazysearch;

import java.util.ArrayList;

import com.android.lazysearch.LazySearch.ImageAdapter.itemViewHolder;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class LazySearch extends Activity {
    /** Called when the activity is first created. */
	
	private Item addedItem;
	private Restaurant selectedRestaurant;
	private ArrayList<Restaurant> selectedRestaurantList;
	private Context mContext;
	private GlobalClass appState;
	private Item selectedItem;
	private ArrayList<Item> items;
	private Gallery gallery;
	private MenuItemsAdapter iAdapter;
	private ImageAdapter imageAdapter;
	private RestaurantGalleryAdapter restAdapter;
	//used to make sure when an activity returns, you get the correct result
	final static int NEW_TAB_REQUEST = 1;
	
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);   
        mContext = this;
    	Toast.makeText(LazySearch.this, "" + "on create", Toast.LENGTH_SHORT).show();
		FrameLayout stub = (FrameLayout)findViewById(R.id.stub_frame);
		LayoutInflater layoutInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		layoutInflater.inflate(R.layout.map_view,stub);

        appState = ((GlobalClass)getApplicationContext());
//        Bundle bundle = this.getIntent().getExtras();
//        if(bundle == null)
//        {
	        selectedRestaurantList = appState.getRestaurantList();
	        selectedRestaurant = appState.getRestaurant();
			items = selectedRestaurant.getRestaurantItems();
	        //selectedRestaurantList.add(selectedRestaurant);
//        }
//        else
//        {
//        	selectedRestaurantList = bundle.getParcelableArrayList("selectedRestaurants");
//	        selectedRestaurant = selectedRestaurantList.get(0);
//        }
       
	        gallery = (Gallery) findViewById(R.id.menu_gallery);
			//gallery for menu items
	        imageAdapter = new ImageAdapter(this);
	        gallery.setAdapter(imageAdapter);	
	        gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
        	public void onClick(View v) {
				
	        }

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				
				itemViewHolder v = (itemViewHolder) arg1.getTag();
				addedItem = v.holderItem;
				//Toast.makeText(LazySearch.this, "" + addedItem.getItemName()+" "+addedItem.getDesc()+" "+addedItem.getItemPrice(), Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
	    });    
    }
        
	public void addButtonClicked(View v)
	{
		boolean flag = true;
		//add current item to selectedRestaurant or just increment qty if already present
		for(int i=0;i<selectedRestaurant.getNumAddedItems();i++)
		{
			if(addedItem.getDesc().toString().equals(selectedRestaurant.getCheckedoutItem(i).getDesc()))
			{
				flag = false;
				int qty = selectedRestaurant.getCheckedoutItem(i).getItemQty();
				selectedRestaurant.getCheckedoutItem(i).setItemQty(qty+1);
				Float total = appState.getTotal();
				total = total + selectedRestaurant.getCheckedoutItem(i).getItemPrice();
				appState.setTotal(total);
				break;
			}
		}
		if(flag)
		{
			addedItem.setItemQty(1);
			Float total = appState.getTotal();
			total = total + addedItem.getItemPrice();
			appState.setTotal(total);
			selectedRestaurant.addToCheckedOutItems(addedItem);	
		}
	}
	
	//start CheckActivity
	public void proceedButtonClicked(View v)
	{
		//add selected restaurant to selectedRestaurantList
		//send restaurant list to the next activity
		final int result = 1;
		Intent intent = new Intent(mContext,CheckActivity.class);
		Bundle bundle = new Bundle();
		bundle.putParcelableArrayList("selectedRestaurants", selectedRestaurantList);
		intent.putExtras(bundle);
		this.startActivityForResult(intent, NEW_TAB_REQUEST);
	}

	//replace map view with thumbnails layout
	public void show_thumbnails(View v)
	{
		FrameLayout stub = (FrameLayout)findViewById(R.id.stub_frame);
		stub.removeAllViews();
		
		LayoutInflater layoutInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		layoutInflater.inflate(R.layout.thumbnails,stub);
        iAdapter = new MenuItemsAdapter(mContext, items);  
        TextView tv = (TextView) findViewById(R.id.restaurantName);
        tv.setText(selectedRestaurant.getRestaurantName());
        GridView gridView = (GridView) findViewById(R.id.grid_tables);
        gridView.setAdapter(iAdapter);
        gridView.setOnItemClickListener(itemClickListener);
	}
	
	//get the selected item to be displayed in the items gallery
    private OnItemClickListener itemClickListener = new OnItemClickListener() 
    {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) 
        {
    		selectedItem = (Item) iAdapter.getItem(position);
    		gallery.setAnimationDuration(10000);
    		gallery.setSelection(position, true);
        }
    };

    //back button from thumbnails to main page
	public void back(View v)
	{
		FrameLayout stub = (FrameLayout)findViewById(R.id.stub_frame);
		stub.removeAllViews();
		LayoutInflater layoutInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		layoutInflater.inflate(R.layout.map_view,stub);
	}

	//back to main page from CheckActivity
	@Override
    public void onActivityResult(int requestCode,int resultCode,Intent data)
    {
    	if(requestCode==NEW_TAB_REQUEST)
    	{
    		Bundle bundle = data.getExtras();
        	selectedRestaurantList = bundle.getParcelableArrayList("selectedRestaurants"); 
        	selectedRestaurant = selectedRestaurantList.get(0);    		
    	}
    }
	
	public class ImageAdapter extends BaseAdapter 
    {
		private Activity activity;
		private LayoutInflater inflater = null;
		private boolean itemFlag;
				
        public ImageAdapter(Activity a) 
        {
            activity = a;
            inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        
        public int getCount() 
        {
        	return items.size();
        }

        public Object getItem(int position) 
        {
            return position;
        }

        public long getItemId(int position) 
        {
            return position;
        }

        public class itemViewHolder 
        {
            public TextView price;
            public TextView desc;
            public TextView name;
            public ImageView itemImage;
            public Button button;
            public Item holderItem;
        }
        
        public View getView(int position, View convertView, ViewGroup parent)
        {
            View vi = convertView;
                itemViewHolder holder;
	            if(convertView == null)
	            {
	                vi = inflater.inflate(R.layout.gallery, null);
	                holder = new itemViewHolder();
	                holder.price = (TextView)vi.findViewById(R.id.price);
	                holder.name = (TextView)vi.findViewById(R.id.name);
	                holder.desc = (TextView)vi.findViewById(R.id.desc);
	                holder.itemImage = (ImageView)vi.findViewById(R.id.image1);
	                holder.button = (Button)vi.findViewById(R.id.button1);
	                vi.setTag(holder);
	            }
	            else
	            {
	                holder = (itemViewHolder)vi.getTag();
	            }
	            
	            holder.desc.setText(items.get(position).getDesc());
	            holder.itemImage.setImageResource(items.get(position).getItemImage());
	            holder.price.setText("$"+items.get(position).getItemPrice());
	            holder.name.setText(items.get(position).getItemName());
	            holder.holderItem = items.get(position);
	            //Toast.makeText(LazySearch.this, "" + holder.desc.getText(), Toast.LENGTH_SHORT).show();
	            return vi;      	
        }
    }
	
	public void showRestaurantGallery(View v)
	{
		
        gallery = (Gallery) findViewById(R.id.menu_gallery);
		restAdapter = new RestaurantGalleryAdapter(this);
		gallery.setAdapter(restAdapter);
	}
	
	public class RestaurantGalleryAdapter extends BaseAdapter 
    {
		private Activity activity;
		private LayoutInflater inflater = null;
				
        public RestaurantGalleryAdapter(Activity a) {
            activity = a;
            inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        
        public int getCount() {
            return selectedRestaurantList.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public class ViewHolder {
            public TextView restaurantName;
            public TextView restaurantAdd;
            public ImageView restaurantImage;
            public ImageView restaurantRating;
            public Item holderRestaurant;
        }
        
        public View getView(int position, View convertView, ViewGroup parent) {
            View vi = convertView;
            ViewHolder holder;
            if(convertView == null)
            {
                vi = inflater.inflate(R.layout.restaurant_gallery, null);
                holder = new ViewHolder();
                holder.restaurantName = (TextView)vi.findViewById(R.id.restName);
                holder.restaurantAdd = (TextView)vi.findViewById(R.id.restAdd);
                holder.restaurantImage = (ImageView)vi.findViewById(R.id.restImage);
                holder.restaurantRating = (ImageView)vi.findViewById(R.id.restRating);
                vi.setTag(holder);
            }
            else
            {
                holder = (ViewHolder)vi.getTag();
            }
            holder.restaurantName.setText(selectedRestaurant.getRestaurantName());
            holder.restaurantImage.setImageResource(selectedRestaurant.getRestaurantImage());
            holder.restaurantRating.setImageResource(selectedRestaurant.getRestaurantRating());
            holder.restaurantAdd.setText(selectedRestaurant.getRestaurantAddress());
            holder.holderRestaurant = items.get(position);
            //Toast.makeText(LazySearch.this, "" + holder.desc.getText(), Toast.LENGTH_SHORT).show();
            return vi;      	
        }
    }
}